"use client";
import { FC, useEffect, useRef, useState } from "react";
import { useRouter } from "@/i18n/routing"; // Assuming router logic
import { GameInfo } from "@/api/home";
import { server } from "@/utils/client";
import { useTranslations } from "next-intl";
import Script from "next/script";

interface Props {
  brand_id: string;
  token: string;
}

const SportsClient: FC<Props> = (props) => {
  const { brand_id, token } = props;
  const [currentToken, setCurrentToken] = useState(token);

  const btRef = useRef(null);
  const router:any = useRouter();

  useEffect(() => {
    if (typeof window !== "undefined") { 
      const script = document.createElement("script");
      script.src = "https://ui.invisiblesport.com/bt-renderer.min.js";
      script.async = true;
      script.onload = () => {
        onLoad();
      };
      document.body.appendChild(script);

      return () => {
        console.log("onLoad=====> Clean up");
        if (btRef.current) {
          // @ts-ignore
          btRef.current?.kill();
          btRef.current = null;
        }
        document.body.removeChild(script); // Remove script when component unmounts
      };
    }
  }, []);
  
  useEffect(() => {
    // 如果token更新了才调用update
    if( currentToken !== token){
      updateToken(token);
    }
  }, [token]);

  const updateToken = (newToken: string) => {
    // @ts-ignore
      if(currentToken!== newToken){
        setCurrentToken(newToken);
        // 多次点击当前页面只需要跳转到首页即可
        // 使用 updateOptions 更新当前的 BTRenderer 参数，而不是重新初始化
        if (btRef.current) {
          // 更新 token 和其他配置
          // @ts-ignore
          btRef.current.updateOptions({
            token: newToken, // 更新 token
            url: '/', // 更新 URL 或其他参数
            betSlipOffsetBottom: 80,
            betSlipZIndex: 1000,
            stickyTop: 0,
            betSlipOffsetTop: 50,
          });
        }
        
      }
  }

  const getGameDetailApi = async () => {
    const data = await server
        .request<GameInfo>({
            url: "/v1/api/front/game_info_by_id",
            method: "post",
            data: { id: "sportsBet", mode: 1 },
        })
        .then((res) => {
            if (res.code === 200) {
              setCurrentToken(res.data.game_url)
              return res.data.game_url;
            } else {
              return "";
            }
        });
    return data;
  };

  const onLoad = () => {
    // @ts-ignore
    const bt = new BTRenderer();
    btRef.current = bt;
    // @ts-ignore
    bt.initialize({
        brand_id: brand_id,
        token: token,//使用最新的token
        onTokenExpired: getGameDetailApi, //过期自动更新token
        onSessionRefresh: () => {
          window.location.reload();
        },
        themeName: "default",
        lang: "pt-br",
        target: document.getElementById("betby"),
        betSlipOffsetBottom: 80,
        // betSlipOffsetRight: 750,
        betSlipZIndex: 1000,
        stickyTop: 0,
        betSlipOffsetTop: 50,
        onRecharge: function () {
            router.push("/deposit");
        },
        onRouteChange: function () {
        },
        onLogin: function () {},
        onRegister: function () {},
        onBetSlipStateChange: function () {},
    });
  };

  return <div id="betby" className="h-[100%]"></div>;
};

export default SportsClient;
